package com.study.rabbitmq.producer.confirm;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class Send2 {
	private final static String QUEUE_NAME = "tanQueue";
	private final static String EXCHANGE_NAME = "tanExchange";

	private final static String ROUTING_KEY = "tan";

	public static void main(String[] args) throws Exception {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("192.168.20.204");
		factory.setPort(5673);
		factory.setUsername("admin");
		factory.setPassword("admin");

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();

		channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, false, false, null);

		Map<String, Object> arguments = new HashMap<>();
		arguments.put("x-message-ttl", 6000);
		channel.queueDeclare(QUEUE_NAME, false, false, false, arguments);


		channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);








		channel.confirmSelect();

		//异步监听 delivertag channel每次投递加1.从1开始。
		channel.addConfirmListener(new ConfirmListener() {
			@Override
			public void handleAck(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("发送成功" +deliveryTag);
			}

			@Override
			public void handleNack(long deliveryTag, boolean multiple) throws IOException {
				System.out.println("发送失败" +deliveryTag);
				//重发 等处理
			}
		});


		String message = "Hello wrorld";
		for (int i = 0; i < 100; i++) {
			channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, (message + i).getBytes());
		}





		channel.close();
		connection.close();
	}
}
